import { ipcMain, BrowserWindow, screen } from 'electron'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import log from 'electron-log'
import windowManager from '../windowManager'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

// 直接从主进程的 index.ts 中导入已经计算好的路径
import { RENDERER_DIST } from '../index'

// 与主窗口使用完全相同的 preload 路径计算
// 编译后所有代码都在 dist-electron/main/index.js 中
// 因此 __dirname 与主窗口相同，使用相同的相对路径
const PRELOAD_PATH = path.join(__dirname, '../preload/index.cjs')

/**
 * 创建直播叫醒悬浮窗
 */
export function createLiveWakeupFloatingWindow() {
  // 如果已经存在，则显示并聚焦
  const existingWindow = windowManager.getLiveWakeupFloatingWindow()
  if (existingWindow && !existingWindow.isDestroyed()) {
    existingWindow.show()
    existingWindow.focus()
    log.info('[悬浮窗] 已存在的悬浮窗获得焦点')
    return existingWindow
  }

  // 打印路径信息用于调试
  log.info('[悬浮窗] 创建配置:')
  log.info('[悬浮窗] - PRELOAD_PATH:', PRELOAD_PATH)
  log.info('[悬浮窗] - RENDERER_DIST:', RENDERER_DIST)
  log.info('[悬浮窗] - VITE_DEV_SERVER_URL:', process.env.VITE_DEV_SERVER_URL)

  // 创建新的悬浮窗
  const floatingWindow = new BrowserWindow({
    width: 360,
    height: 420,
    frame: false, // 无边框
    transparent: false,
    alwaysOnTop: true, // 始终置顶
    resizable: false,
    skipTaskbar: true, // 不显示在任务栏
    webPreferences: {
      preload: PRELOAD_PATH,
      sandbox: false,
      nodeIntegration: false,
      contextIsolation: true,
    },
  })

  // 打开开发者工具用于调试（仅开发环境）
  if (process.env.VITE_DEV_SERVER_URL) {
    floatingWindow.webContents.openDevTools({ mode: 'detach' })
  }

  // 加载页面
  if (process.env.VITE_DEV_SERVER_URL) {
    const url = `${process.env.VITE_DEV_SERVER_URL}#/live-wakeup-floating`
    log.info('[悬浮窗] 加载开发服务器 URL:', url)
    floatingWindow.loadURL(url)
  } else {
    const htmlPath = path.join(RENDERER_DIST, 'index.html')
    log.info('[悬浮窗] 加载生产文件:', htmlPath)
    floatingWindow.loadFile(htmlPath, {
      hash: '/live-wakeup-floating',
    })
  }

  // 监听页面加载完成
  floatingWindow.webContents.on('did-finish-load', () => {
    log.info('[悬浮窗] 页面加载完成')
  })

  // 监听加载失败
  floatingWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    log.error('[悬浮窗] 页面加载失败:', errorCode, errorDescription)
  })

  // 保存到窗口管理器
  windowManager.setLiveWakeupFloatingWindow(floatingWindow)

  log.info('[悬浮窗] 直播叫醒悬浮窗已创建')

  return floatingWindow
}

/**
 * 关闭悬浮窗
 */
export function closeLiveWakeupFloatingWindow() {
  const floatingWindow = windowManager.getLiveWakeupFloatingWindow()
  if (floatingWindow && !floatingWindow.isDestroyed()) {
    floatingWindow.close()
    log.info('[悬浮窗] 直播叫醒悬浮窗已关闭')
  }
}

// 存储屏幕区域选择窗口的引用
let regionSelectionWindow: BrowserWindow | null = null

/**
 * 创建屏幕区域选择窗口
 */
export function createScreenRegionSelector(): Promise<{ x: number; y: number; width: number; height: number } | null> {
  return new Promise((resolve) => {
    // 如果已经存在选择窗口，先关闭
    if (regionSelectionWindow && !regionSelectionWindow.isDestroyed()) {
      regionSelectionWindow.close()
    }

    // 获取主显示器信息
    const primaryDisplay = screen.getPrimaryDisplay()
    const { width, height } = primaryDisplay.bounds
    const scaleFactor = primaryDisplay.scaleFactor
    
    log.info('[屏幕区域选择] 显示器信息:', {
      bounds: primaryDisplay.bounds,
      scaleFactor: scaleFactor,
      size: primaryDisplay.size,
    })

    // 创建全屏透明窗口
    regionSelectionWindow = new BrowserWindow({
      width,
      height,
      x: 0,
      y: 0,
      frame: false,
      transparent: true,
      alwaysOnTop: true,
      skipTaskbar: true,
      resizable: false,
      movable: false,
      minimizable: false,
      maximizable: false,
      fullscreen: false, // 改为 false，使用手动设置尺寸
      show: false, // 先不显示，加载完成后再显示
      webPreferences: {
        preload: PRELOAD_PATH,
        nodeIntegration: false,
        contextIsolation: true,
        webSecurity: false,
        // 🔧 禁用缩放，使窗口使用实际屏幕尺寸
        zoomFactor: 1.0,
      },
    })

    // 手动最大化窗口
    regionSelectionWindow.maximize()
    regionSelectionWindow.setAlwaysOnTop(true, 'screen-saver')
    
    // 🔧 将显示器缩放因子传递给渲染进程
    regionSelectionWindow.webContents.once('did-finish-load', () => {
      regionSelectionWindow?.webContents.send('screen-region-selector:scaleFactor', scaleFactor)
    })

    // 加载区域选择页面
    if (process.env.VITE_DEV_SERVER_URL) {
      regionSelectionWindow.loadURL(`${process.env.VITE_DEV_SERVER_URL}#/screen-region-selector`)
    } else {
      regionSelectionWindow.loadFile(path.join(RENDERER_DIST, 'index.html'), {
        hash: '/screen-region-selector',
      })
    }

    // 页面加载完成后显示窗口
    regionSelectionWindow.once('ready-to-show', () => {
      if (regionSelectionWindow && !regionSelectionWindow.isDestroyed()) {
        regionSelectionWindow.show()
        regionSelectionWindow.focus()
        log.info('[屏幕区域选择] 窗口已显示')
      }
    })

    let isResolved = false // 防止重复resolve

    // 监听区域选择结果
    const handleRegionSelected = (_event: any, region: { x: number; y: number; width: number; height: number } | null) => {
      if (isResolved) return // 已经处理过了
      
      log.info('[屏幕区域选择] 收到选择结果:', region)
      isResolved = true
      resolve(region)
      
      // 立即清理监听器
      ipcMain.removeListener('screen-region-selector:result', handleRegionSelected)
      ipcMain.removeListener('screen-region-selector:cancel', handleRegionCancelled)
      
      // 关闭选择窗口
      if (regionSelectionWindow && !regionSelectionWindow.isDestroyed()) {
        regionSelectionWindow.close()
        regionSelectionWindow = null
      }
    }

    // 监听取消选择
    const handleRegionCancelled = () => {
      if (isResolved) return // 已经处理过了
      
      log.info('[屏幕区域选择] 用户取消选择')
      isResolved = true
      resolve(null)
      
      // 立即清理监听器
      ipcMain.removeListener('screen-region-selector:result', handleRegionSelected)
      ipcMain.removeListener('screen-region-selector:cancel', handleRegionCancelled)
      
      // 关闭选择窗口
      if (regionSelectionWindow && !regionSelectionWindow.isDestroyed()) {
        regionSelectionWindow.close()
        regionSelectionWindow = null
      }
    }

    // 先清理可能存在的旧监听器
    ipcMain.removeAllListeners('screen-region-selector:result')
    ipcMain.removeAllListeners('screen-region-selector:cancel')

    // 注册事件监听器
    ipcMain.on('screen-region-selector:result', handleRegionSelected)
    ipcMain.on('screen-region-selector:cancel', handleRegionCancelled)

    // 窗口关闭时清理
    regionSelectionWindow.on('closed', () => {
      regionSelectionWindow = null
      // 清理事件监听器
      ipcMain.removeListener('screen-region-selector:result', handleRegionSelected)
      ipcMain.removeListener('screen-region-selector:cancel', handleRegionCancelled)
    })

    log.info('[屏幕区域选择] 屏幕区域选择窗口已创建')
  })
}

/**
 * 设置悬浮窗 IPC 处理器
 */
export function setupFloatingWindowIpcHandlers() {
  // 打开悬浮窗
  ipcMain.handle(IPC_CHANNELS.liveWakeup.openFloatingWindow, () => {
    try {
      createLiveWakeupFloatingWindow()
      return { success: true }
    } catch (error) {
      log.error('[悬浮窗] 打开失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误',
      }
    }
  })

  // 关闭悬浮窗
  ipcMain.handle(IPC_CHANNELS.liveWakeup.closeFloatingWindow, () => {
    closeLiveWakeupFloatingWindow()
    return { success: true }
  })

  // 屏幕区域选择
  ipcMain.handle('liveWakeup:selectScreenRegion', async () => {
    try {
      log.info('[屏幕区域选择] 开始区域选择')
      const region = await createScreenRegionSelector()
      return {
        success: true,
        region,
      }
    } catch (error) {
      log.error('[屏幕区域选择] 选择失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '未知错误',
      }
    }
  })

  log.info('[悬浮窗] IPC处理器已注册')
}

